import datetime

import django.http as http
import django.shortcuts as shortcuts
from django.template import RequestContext
from django.core.urlresolvers import reverse
from django.contrib.contenttypes.models import ContentType

from core.models import Request
from tagging.utils import parse_tag_input
from tagging.models import Tag
from django_multivoting.models import Vote, Popularity
import django_utils.pagination as pagination
import django_utils.request_helpers as request_helpers
from django_community.models import UserProfile
from django.contrib.auth.models import User

def main(request):
    return shortcuts.render_to_response('core/main.html',
                                        {},
                                        context_instance = RequestContext(request))
    
def requests(request, mode, sort_option):
    page = request_helpers.get_page(request)
    
    today = datetime.date(1,  1,  1).today()
    last_week = today - datetime.timedelta(days = 7)
    date = "'" + last_week.isoformat() + "'"
    
    if sort_option == 'newest':
        objects = Request.objects.filter(mode = mode).order_by('-date_created')
    elif sort_option == 'popular':
        objects = Vote.objects.most_popular_objects(Request).filter(mode = mode)
    elif sort_option == 'active':
        objects = Vote.objects.most_active_objects(Request, date).filter(mode = mode)
    elif sort_option == 'completed':
        objects = Request.objects.filter(mode = mode, status = 'Completed').order_by('-date_created')

    if not sort_option == 'completed':
        objects = objects.exclude(status = 'Completed')
        
    paginator = pagination.DiggPaginator(objects, 10, body=5)
    current_page = paginator.page(page)
    page_range = paginator.page_range
    object_count = len(current_page.object_list)
    
    if mode == 'Feature':
        if sort_option == 'completed':
            site_section = 'completed_features'
        else:
            site_section = 'features'
    elif mode == 'Bug':
        if sort_option == 'completed':
            site_section = 'closed_bugs'
        else:
            site_section = 'bugs'
        
    return shortcuts.render_to_response(
                            'core/features.html',
                            {'current_page':current_page,  'page_range':page_range, 'sort':sort_option, 'mode':mode, 'site_section':site_section},
                            context_instance = RequestContext(request))

def request_details(request, request_id):
    from django_comments.forms import CommentForm
    
    content_type_object = ContentType.objects.get_for_model(Request)
    object = Request.objects.get(id = request_id)
    object.popularity = Vote.objects.popularity(object)
    object.supporters = Vote.objects.filter(content_type = content_type_object, object_id = object.id, mode = 'up')
    comment_form = CommentForm()
    return shortcuts.render_to_response(
                    'core/request_details.html',
                    {'object':object, 'comment_form':comment_form},
                    context_instance = RequestContext(request))

def submit(request):
    from core.forms import RequestForm
    
    if request.POST:
        form = RequestForm(request.POST, request.FILES, request)
        if form.is_valid():
            request_content_type = ContentType.objects.get_for_model(Request)
            request = Request(name = form.cleaned_data['name'], 
                              url = form.cleaned_data['url'],
                              description = form.cleaned_data['description'],
                              mode = form.cleaned_data['mode'],
                              user = request.user)
            request.save()
            
            popularity = Popularity(content_type = request_content_type, object_id = request.id)
            popularity.save()
            tags = parse_tag_input(form.data_cleaned['tags'])
            for tag in tags:
                Tag.objects.add_tag(request, tag)
            return http.HttpResponseRedirect(reverse('details',  args=[request.id]))
    else:
        form = RequestForm()
    return shortcuts.render_to_response(
                'core/submit.html', 
                {'form':form}, 
                context_instance = RequestContext(request),
    )
    
def relevant_requests(request, user_id):
    page = request_helpers.get_page(request)
    
    user_object = shortcuts.get_object_or_404(User, id = user_id)
    objects = Vote.objects.voted_objects_by_user(user, Request)
    current_page,  page_range = pagination.paginate_queryset_ajax(objects,  10,  5,  page,  "%requests_page_", 
                            reverse('community-relevant-requests',  args=[user_object.id]))
    
    return shortcuts.render_to_response(
                'django_community/elements/relevant_requests.html', 
                {'current_page':current_page, 'page_range':page_range}, 
                context_instance = RequestContext(request),
    )